<template>
    <div class="common-layout">
      <el-container>
        <el-main>
            <el-table :data="state.data" height="700" 
            :cell-class-name="tableCellClassName"
            @sort-change="sortChange"
            :default-sort="state.sort"
            @cell-click="cellClick"
            style="width: 100%">
                <el-table-column prop="year" label="年度" sortable width="100" fixed/>
                <el-table-column v-if="stockCategory=='股票'" prop="wugu" label="吾股" sortable />
                <el-table-column prop="yearPct" label="年度表现" />
                <el-table-column prop="minYearPct" label="年最大跌幅" sortable />
                <el-table-column prop="minDate" label="最低点日期" width="200" />
                <el-table-column prop="maxYearPct" label="年最大涨幅" sortable/>
                <el-table-column prop="maxDate" label="最高点日期" width="200"/>
                <el-table-column prop="minDrawDown" label="minDrawDown" sortable/>
                <el-table-column prop="minDrawDownDate" label="minDrawDownDate" width="140" />
            </el-table>
        </el-main>
      </el-container>
    </div>
</template>

<script setup>
import { reactive, watch } from 'vue';
import { weekStockSearch } from '../stores/week'
import { getYearPct } from '../service/year'
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router'
import { openNewTableDDisplay } from '../router';

const base = "yearStockDetail"
const sortPropKey = base + "SortProp"
const sortOrderKey = base + "SortOrder"

const stockSearchStore = weekStockSearch()
let { input } = storeToRefs(stockSearchStore)

// 网址传参
const {query: query} = useRoute()
if(query.stock) {
    input.value = query.stock
}

const props = defineProps({
    stockCategory: String
})

const state = reactive({
    data: [],
    sort: { 
        prop: sessionStorage.getItem(sortPropKey) || 'date' , 
        order: sessionStorage.getItem(sortOrderKey) || 'descending' 
    }
})

const loadData = () => {
    getYearPct(input.value).then( res => {
        state.data = res.data
    })
}

loadData()

// 只监听pinia中某一个值的变化
watch(() => input.value, (newValue, oldValue) => {
    loadData()
})

const sortChange = (column, prop, order) => {
    sessionStorage.setItem(sortPropKey, column.prop)
    sessionStorage.setItem(sortOrderKey, column.order)
}

const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    let columnProperty = column.property
    if (columnProperty == "yearPct") {
        if (row.yearPct < 0) {
            return "pctlt0-cell";
        }
    }
    return ''
}

const cellClick = (row, column, cell, event) => {
    let columnProperty = column.property
    let val = row[columnProperty]

    if (["minDrawDownDate", "maxDate", "minDate"].includes(columnProperty)) {
        openNewTableDDisplay(input.value , val)
    }
}
</script>

<style>
</style>